import { fileURLToPath, URL } from 'node:url'

import {ConfigEnv, defineConfig, loadEnv} from 'vite'
import vue from '@vitejs/plugin-vue'
import vueDevTools from 'vite-plugin-vue-devtools'
import process from "node:process";
import Unocss from 'unocss/vite'
import { createVitePlugins } from './plugins'

// 输出目录
const OUTPUT_DIR = 'dist'
export default defineConfig(({ mode }: ConfigEnv) => {
    // 加载 .env 文件中的环境变量
    const env = loadEnv(mode, process.cwd())
    // 获取 src 路径
    const baseSrc = fileURLToPath(new URL('./src', import.meta.url))
    // 代理配置（仅开发环境）
    const proxyObj: Record<string, any> = {}
    if (mode === 'development') {
        const { VITE_APP_BASE_API_DEV, VITE_APP_BASE_URL_DEV } = env
        if (VITE_APP_BASE_API_DEV && VITE_APP_BASE_URL_DEV) {
            proxyObj[VITE_APP_BASE_API_DEV] = {
                target: VITE_APP_BASE_URL_DEV,
                changeOrigin: true,
                rewrite: (path: string) => path.replace(new RegExp(`^${VITE_APP_BASE_API_DEV}`), ''),
            }
        }
    }
    return {
        /*plugins: [
            vue(),
            vueDevTools(),
            Unocss(),
        ],*/
        plugins: createVitePlugins(env),
        resolve: {
            alias: {
                '@': fileURLToPath(new URL('./src', import.meta.url)),
                '~@': baseSrc,
                '~': baseSrc,
            },
        },
        build: {
            outDir: OUTPUT_DIR,
            chunkSizeWarningLimit: 4096,
            rollupOptions: {
                output: {
                    manualChunks: {
                        vue: [
                            'vue',
                            'vue-router',
                            'pinia',
                            'vue-i18n',
                            '@vueuse/core'
                        ],
                        ui: [
                            'ant-design-vue',
                            '@ant-design/icons-vue'
                        ],
                        utils: ['lodash-es', 'dayjs']
                    }
                }
            }
        },
        server: {
            open: true, // ✅ 启动时自动打开浏览器
            proxy: proxyObj,
        }
    }
})
